package com.creatshare.controller;

import java.time.LocalDateTime;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.creatshare.bean.Bug;
import com.creatshare.bean.Page;
import com.creatshare.util.ResultInfo;

/**
 * @author xianyijun
 *
 */
@Controller
public class BugController extends BaseController {

	@RequestMapping(value = "/bug", method = RequestMethod.POST)
	public @ResponseBody Object insert(Bug bug) {
		bug.setBugstate(0);
		bug.setCreatetime(LocalDateTime.now().toString());
		int flag = bugService.insert(bug);
		if (flag != 0) {
			resultInfo.setCode(1);
			resultInfo.setData(ResultInfo.BUG_INSERT_SUCCESS);
		} else {
			resultInfo.setCode(-1);
			resultInfo.setData(ResultInfo.BUG_INSERT_ERROR);
		}
		return JSONObject.toJSON(resultInfo);
	}

	@RequestMapping(value = "/bug/{bugid:[\\d+]}", method = RequestMethod.PUT)
	public @ResponseBody Object update(Bug bug) {
		int flag = bugService.update(bug);
		System.out.println(flag);
		if (flag != 0) {
			resultInfo.setCode(1);
			resultInfo.setData(bug);
		} else {
			resultInfo.setCode(-1);
			resultInfo.setData(ResultInfo.BUG_UPDATE_ERROR);
		}
		return JSONObject.toJSON(resultInfo);
	}

	@RequestMapping(value = "/bug/{bugid:[\\d]+}", method = RequestMethod.GET)
	public @ResponseBody Object show(@PathVariable int bugid) {
		Bug bug = bugService.getBugById(bugid);
		if(bug==null){
			resultInfo.setCode(-1);
			resultInfo.setData(ResultInfo.BUG_NOT_EXIST);
		}else{
			resultInfo.setCode(1);
			resultInfo.setData(bug);
		}
		return JSONObject.toJSON(resultInfo);
	}

	@RequestMapping(value = "/bugs", method = RequestMethod.GET)
	public @ResponseBody Object getByState(@RequestParam(value = "bugstate", defaultValue = "0") int bugstate,
			@RequestParam(value = "projectid", defaultValue = "0") int projectid,
			@RequestParam(value = "currentPage", defaultValue = "1") int currentPage) {
		Page page = null;
		// 根据state查找
		if (bugstate != 0) {
			page = bugService.getBugByState(currentPage, bugstate);
		}
		// 根据 projectid 查找
		else if (projectid != 0) {
			page = bugService.getBugByPro(currentPage, projectid);
		}
		// 默认返回最近发布的
		else {
			page = bugService.getBugByLater(currentPage);
		}
		resultInfo.setCode(1);
		resultInfo.setData(page);
		return JSONObject.toJSON(resultInfo);
	}
}
